package com.google.precinct.client.mapper;

import com.google.precinct.client.Util;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.geocode.Geocoder;
import com.google.gwt.maps.client.geocode.LocationCallback;
import com.google.gwt.maps.client.geocode.Placemark;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class Map1CityListPanelContents extends Composite {

	private static PrecinctMapFirstStepPaneUiBinder uiBinder = GWT
			.create(PrecinctMapFirstStepPaneUiBinder.class);

	interface PrecinctMapFirstStepPaneUiBinder extends
			UiBinder<Widget, Map1CityListPanelContents> {
	}

	private final MapPrecinctRootPanel ctr;

	private final MapWidget maps;

	@UiField
	Label precinctNoLabel;

	@UiField
	Label postOperationLabel;

	@UiField
	TextBox province;

	@UiField
	TextBox municipality;

	@UiField
	Button addressSearch;

	public Map1CityListPanelContents(MapPrecinctRootPanel ctr,
			MapWidget maps,
			String precinctNo) {
		this.ctr = ctr;
		initWidget(uiBinder.createAndBindUi(this));

		this.maps = maps;
		precinctNoLabel.setText(precinctNo);
	}

	public Map1CityListPanelContents(MapPrecinctRootPanel precinctMapPage,
			MapWidget maps, String precinctNo, String province,
			String municipality) {
		this(precinctMapPage, maps, precinctNo);
		this.province.setText(province);
		this.municipality.setText(municipality);
	}

	@UiHandler("addressSearch")
	void onAddressSearch(ClickEvent e) {
		int zoom = maps.getZoomLevel();
		boolean notEmpty = false;
		String address = "Philippines";
		if (province.getText().trim().length() > 0) {
			zoom = 9;
			notEmpty = true;
			address = province.getText().trim() + ", " + address;
		}
		if (municipality.getText().trim().length() > 0) {
			zoom = 11;
			notEmpty = true;
			address = municipality.getText().trim() + ", " + address;
		}
		if (!notEmpty) return;
		Geocoder gcoder = new Geocoder();
		gcoder.setBaseCountryCode("ph");
		final int zoomLevel = zoom;
		gcoder.getLocations(address, new LocationCallback() {

			@Override
			public void onSuccess(JsArray<Placemark> locations) {
				// TODO Support multiple locations
				if (locations.length() > 0) {
					Util.track("/PrecinctFinder/03-AddressSelect");
					maps.setCenter(locations.get(0).getPoint(), zoomLevel);
					ctr.selectedAddress(province.getText(), municipality.getText());
				} else {
					// TODO Display no found locations
				}
			}

			@Override
			public void onFailure(int statusCode) {
				// TODO Report the error
			}
		});
	}


}
